package crud

import (
	"encoding/json"
	"path/filepath"
	"strings"

	"api/system/cmd"
	"api/system/helper"
	"github.com/fatih/color"
)

const DS = string(filepath.Separator)

var join = helper.Join

type cGlobal struct {
	Ds, RootPath, TableName, ModuleName, AppPath                             string
	ControllerPath, ServicePath, ModelPath, ValidatePath                     string
	ControllerNameSpace, ServiceNameSpace, ModelNameSpace, ValidateNameSpace string
	Field                                                                    cmd.MMapStr
	HasModel                                                                 bool
}

func New(p *cmd.CmdParam) *cGlobal {
	g := new(cGlobal)
	color.Green("即将开始初始化...")
	g.Init(p)
	color.Green("即将初始化完成.")

	return g
}

func (g *cGlobal) String() string {
	by, _ := json.Marshal(*g)

	return string(by)
}

func (g *cGlobal) Init(p *cmd.CmdParam) {
	rootPath := p.Path     // 生成项目的根路径
	tableName := p.Table   // 表名
	moduleNames := p.Group // 模块名称，默认为 admin

	appPath := join(DS, rootPath, "app") // app路径

	g.RootPath = rootPath
	g.AppPath = appPath
	g.TableName = tableName
	g.ModuleName = moduleNames
	g.HasModel = p.HasModel
	g.ControllerNameSpace = g.getNamespace(p.Controller)
	g.ModelNameSpace = g.getNamespace(p.Model)
	g.ServiceNameSpace = g.getNamespace(p.Service)
	g.ValidateNameSpace = p.Validate

	g.ControllerPath = join(DS, rootPath, p.Controller) + ".php"
	g.ServicePath = join(DS, rootPath, p.Service) + ".php"
	g.ModelPath = join(DS, rootPath, p.Model) + ".php"
	g.ValidatePath = join(DS, rootPath, p.Validate)
	g.Ds = DS
	g.Field = p.Field
}

func (g *cGlobal) getNamespace(p string) string {
	inx := strings.LastIndex(p, "\\")

	return p[:inx]
}

func (g *cGlobal) getNameSpaceByType(cns string, ctype string) string {
	flag := false
	if ctype == "controller" || ctype == "model" || ctype == "validate" || ctype == "service" {
		flag = true
	} else {
		flag = false
	}

	if flag {
		if strings.Index(g.TableName, "_") > 0 {
			inx := strings.LastIndex(g.TableName, "_")
			nName := g.TableName[inx+1:]

			cinx := strings.LastIndex(cns, "\\")
			cName := strings.ToLower(cns[cinx+1:])

			if nName == cName {
				cns = strings.ToLower(cns[:cinx])
			}
		} else {
			cinx := strings.LastIndex(cns, "\\")
			cName := strings.ToLower(cns[cinx+1:])

			if g.TableName == cName {
				cns = strings.ToLower(cns[:cinx])
			}
		}
	}

	return cns
}
